package cn.sanch.org.service.impl;

import cn.sanch.basic.service.impl.BaseServiceImpl;
import cn.sanch.basic.util.BaiduAuditUtils;
import cn.sanch.basic.util.BusinessException;
import cn.sanch.basic.util.MD5Utils;
import cn.sanch.basic.util.StrUtils;
import cn.sanch.org.domain.Employee;
import cn.sanch.org.domain.Shop;
import cn.sanch.org.domain.ShopAuditLog;
import cn.sanch.org.dto.ShopDto;
import cn.sanch.org.mapper.EmployeeMapper;
import cn.sanch.org.mapper.ShopAuditLogMapper;
import cn.sanch.org.mapper.ShopMapper;
import cn.sanch.org.service.IShopService;
import cn.sanch.user.domain.Logininfo;
import cn.sanch.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;


/**
 * @author sanch37
 * 2022/5/23
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {


    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 商家入驻
     * @param shop Shop shop
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void settlement(Shop shop) {
        /*
         * 一.校验
         *
         * 1.空值校验:isEmpty():是不是为空：为空返回true
         * 检验店铺信息以及管理员信息
         */
        if (
                StringUtils.isEmpty(shop.getName())
                || StringUtils.isEmpty(shop.getTel())
                || StringUtils.isEmpty(shop.getAddress())
                || StringUtils.isEmpty(shop.getEmployee().getUsername())
                || StringUtils.isEmpty(shop.getEmployee().getEmail())
                || StringUtils.isEmpty(shop.getEmployee().getPhone())
                || StringUtils.isEmpty(shop.getEmployee().getPassword())

        ) {
            throw new BusinessException("数据不能为空!");
        }

        //2.密码校验：两次输入的密码是否一致


        //3.店铺名合规检验
        Boolean aBoolean = BaiduAuditUtils.TextCensor(shop.getName());
        if (!aBoolean) {
            throw new BusinessException("店铺名不合规!请填写合规名字重新提交！");
        }


        //4.是否曾经入驻过：怎么判断入驻过？店铺名 + 地址 + 电话
        Shop shopTmp = shopMapper.loadByMessage(shop);
        if (shopTmp != null) {
            throw new BusinessException("您已经入驻过本平台，请直接登录！如忘记密码请联系管理员！");
        }


        /*
            二：添加到数据库
            1.添加employee
                获取employee对象
         */
        Employee employee = shop.getEmployee();
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        //调用工具类给密码加盐加密
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        employeeMapper.save(employee);


        /*
            2.添加shop
                获取employee对象的id设置给shop的admin_id
                因为shop对象除了admin_id其他都通过前端页面传过来映射给实体类了
                刚好admin_id就等于employee的id
         */
        shop.setAdmin_id(employee.getId());
        shopMapper.save(shop);


        /*
            3.保存登录信息到logininfo
         */
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);


        /*
            3.更新店铺的id到employee
         */
        employee.setShop_id(shop.getId());

        employee.setLogininfo_id(logininfo.getId());

        employeeMapper.update(employee);

    }


    /**
     * 将employee同步到logininfo
     * @param employee
     * @return
     */
    private Logininfo employee2Logininfo(Employee employee) {
        //创建一个Logininfo对象
        Logininfo logininfo = new Logininfo();
        //调用工具类同步
        BeanUtils.copyProperties(employee, logininfo);
        //当前employee为管理员
        logininfo.setType(0);

        return logininfo;
    }

    /**
     * 店铺审核通过
     * @param log
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void pass(ShopAuditLog log) throws MessagingException {
        /*
        1.修改店铺状态
         */
        //前端传过来的日志对象log里面含有店铺id，通过店铺id找到店铺对象
        Shop shop = shopMapper.findOne(log.getShopId());
        //2表示店铺审核通过待激活
        shop.setState(2);
        //更新数据库店铺状态
        shopMapper.update(shop);

        /*
        2.添加日志到数据库
         */
        //设置日志里店铺的状态为2
        log.setState(2);
        //设置审核的平台管理员
        log.setAuditId(325L);
        //添加日志到数据库
        shopAuditLogMapper.save(log);

        /*
        3.发送审核通过激活邮件
         */
        //创建一个复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送人
        helper.setFrom("3049903126@qq.com");
        //设置主题
        helper.setSubject("店铺激活邮件");
        //设置内容
        helper.setText("<h1>恭喜，您的店铺审核通过！！！点击激活店铺</h1>" +
                "<img src='http://123.207.27.208:80"+shop.getLogo() +"'></img>" +
                    "<a href='http://172.16.10.68:8081/#/activate/?"+shop.getId() +"'>点击该链接激活</a>",true);
        //设置接收人
        Employee employee = employeeMapper.findOne(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("sanch3737@163.com");
        //发送复杂邮件
        javaMailSender.send(mimeMessage);

    }

    /**
     * 店铺审核驳回
     * @param log
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reject(ShopAuditLog log) throws MessagingException {

        /*
        1.修改店铺状态
         */
        //前端传过来的日志对象log里面含有店铺id，通过店铺id找到店铺对象
        Shop shop = shopMapper.findOne(log.getShopId());
        //4表示店铺审核驳回
        shop.setState(4);
        //更新数据库店铺状态
        shopMapper.update(shop);

        /*
        2.添加日志到数据库
         */
        //设置日志里店铺的状态为4
        log.setState(4);
        //设置审核的平台管理员
        log.setAuditId(325L);
        //添加日志到数据库
        shopAuditLogMapper.save(log);

        /*
        3.发送审核通过激活邮件
         */
        //创建一个复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送人
        helper.setFrom("3049903126@qq.com");
        //设置主题
        helper.setSubject("店铺驳回邮件");
        //设置内容
        helper.setText("<h1>入驻失败！</h1>" +
                "<a href='http://localhost:8081/#/register'>点击重新入驻</a>",true);
        //设置接收人
        Employee employee = employeeMapper.findOne(shop.getAdmin_id());
        //helper.setTo(employee.getEmail());
        helper.setTo("sanch3737@163.com");
        //发送复杂邮件
        javaMailSender.send(mimeMessage);

        /*
        4.删除店铺入驻的信息和管理员信息
         */
        //删除店铺管理员
        employeeMapper.delete(shop.getAdmin_id());
        //删除店铺信息
        shopMapper.delete(shop.getId());
    }

    /**
     * 获取店铺每一种状态的数量
     * @return
     */
    @Override
    public List<ShopDto> getShopStates() {
        return shopMapper.getShopStates();
    }
}
